﻿using MySqlX.XDevAPI;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace JrpcTest
{
	internal class JsonRpcInterfacesInfo
	{
		public string Version = "0.0.0";
		//static readonly string _strJsonRpcInterfacesInfoFileName = "interfaces.inf";
		private JObject? _joInterfacesInfo;

		Dictionary<string, JsonRpcFunctionInfo> _dctFunctions = new();

		public JsonRpcInterfacesInfo()
		{
		}

		public List<string> GetInterfaceList()
		{
			return _joInterfacesInfo!["interfaces"]!.Select(x => (x as JObject)!["name"]!.ToString()).ToList();
		}

		public JArray GetInterfaceFunctionParams(string strFuncName)
		{
			return (_joInterfacesInfo!.SelectToken($"$.interfaces[?(@.name == '{strFuncName}')].params")! as JArray)!;
		}

		public string GetInterfaceVersion()
		{
			return _joInterfacesInfo!.SelectToken("$.version")!.ToString();
		}

		public void InsertFunctionInfo(JsonRpcFunctionInfo funcInfo)
		{
			_dctFunctions[funcInfo.FuncName] = funcInfo;
		}

		public void SetJsonRpcInterfacesInfo(JObject joInterfacesInfo)
		{
			JObject joInterfaces = (joInterfacesInfo["interfaces"] as JObject)!;
			JArray jaInterfaces = new JArray();

			foreach (var oItem in joInterfaces)
			{
				string strInterface = oItem.Key.ToString();

				JObject joInterface = new JObject();
				joInterface["name"] = strInterface;
				joInterface["params"] = oItem.Value;

				jaInterfaces.Add(joInterface);
			}

			_joInterfacesInfo = new JObject
			{
				["interfaces"] = jaInterfaces,
				["version"] = joInterfacesInfo["version"]
			};
		}

		//public JsonRpcFunctionInfo this[string funcName]
		//{
		//	get
		//	{
		//		if (_dctFunctions.TryGetValue(funcName, out JsonRpcFunctionInfo? info) == true)
		//		{
		//			return info;
		//		}

		//		throw new IndexOutOfRangeException($"Not fount function name: {funcName}");
		//	}
		//}
	}
}
